package com.neuedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.common.BaseContext;
import com.neuedu.common.Result;
import com.neuedu.dto.OrdersDto;
import com.neuedu.dto.OrdersGoodsDto;
import com.neuedu.neuedu_mall.pojo.*;
import com.neuedu.pojo.*;
import com.neuedu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/orders")
@CrossOrigin
@RestController
public class OrdersController {

    @Autowired
    private OrdersService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSpecService goodsSpecService;
    @Autowired
    private OrdersGoodsService ordersGoodsService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressService addressService;


    /**
     * 查询订单列表
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<OrdersDto>> get() {

        // 获取当前登录用户下的所有订单
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getCreateUser, userId);
        List<Orders> orders = orderService.list(ordersLambdaQueryWrapper);

        // 在订单中添加商品信息
        List<OrdersDto> ordersDtos = orders.stream().map(order -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            // 获取订单中的商品信息
            LambdaQueryWrapper<OrdersGoods> ordersGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersGoodsLambdaQueryWrapper.eq(OrdersGoods::getOrdersId, order.getId());


            List<OrdersGoods> ordersGoods = ordersGoodsService.list(ordersGoodsLambdaQueryWrapper);


            // 为订单中的商品信息绑定SKU信息
            List<OrdersGoodsDto> ordersGoodsDtos = getSku(ordersGoods);
            ordersDto.setOrdersGoodsDtos(ordersGoodsDtos);
            return ordersDto;
        }).collect(Collectors.toList());
        return Result.success(ordersDtos);
    }

    /**
     * 查询某订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<OrdersDto> getOneById(@PathVariable Long id) {
        Orders order = orderService.getById(id);
        OrdersDto ordersDto = new OrdersDto();
        BeanUtils.copyProperties(order, ordersDto);
        // 获取订单中的商品信息
        LambdaQueryWrapper<OrdersGoods> ordersGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersGoodsLambdaQueryWrapper.eq(OrdersGoods::getOrdersId, order.getId());

        // 封装地址信息
        Address address = addressService.getById(order.getAddressId());

        List<OrdersGoods> ordersGoods = ordersGoodsService.list(ordersGoodsLambdaQueryWrapper);

        List<OrdersGoodsDto> ordersGoodsDtos = getSku(ordersGoods);
        ordersDto.setOrdersGoodsDtos(ordersGoodsDtos);
        ordersDto.setAddress(address);


        return Result.success(ordersDto);
    }

    /**
     * 取消某订单
     *
     * @param id
     * @return
     */
    @DeleteMapping()
    public Result<String> deleteOneById(@RequestParam Long id) {
        //删除订单
        boolean isDelete = orderService.removeById(id);

        if (!isDelete)
            return Result.error("删除订单失败");

        //删除订单商品关系
        LambdaQueryWrapper<OrdersGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrdersGoods::getOrdersId, id);
        boolean isOrdersGoodsDeleted = ordersGoodsService.remove(lambdaQueryWrapper);

        if (isOrdersGoodsDeleted)
            return Result.success("删除失败");
        else
            return Result.error("删除订单商品失败");
    }

    /**
     * 添加订单
     *
     * @param ordersDto
     * @return
     */
    @PostMapping
    @Transactional
    public Result<String> addOrder(@RequestBody OrdersDto ordersDto) {

        Orders order = new Orders();
        BeanUtils.copyProperties(ordersDto, order, "ordersGoodsDtos");
        // 设置订单状态
        order.setStatus("未支付");
        // 创建订单信息
        boolean isSaved = orderService.save(order);
        // 保存订单和商品的信息
        Long orderId = order.getId();
        List<OrdersGoodsDto> ordersGoodsDtos = ordersDto.getOrdersGoodsDtos();


        List<OrdersGoods> ordersGoods = new ArrayList<>();
        for (OrdersGoodsDto ordersGoodsDto : ordersGoodsDtos) {
            OrdersGoods ordersGoodsTmp = new OrdersGoods();
            ordersGoodsTmp.setSpecId(ordersGoodsDto.getSpecId());
            ordersGoodsTmp.setNumber(ordersGoodsDto.getNumber());
            ordersGoodsTmp.setOrdersId(orderId);
            ordersGoods.add(ordersGoodsTmp);
        }

        ordersGoodsService.saveBatch(ordersGoods);
        // 删除购物车中的商品
        for (OrdersGoods ordersGood : ordersGoods) {
            LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getSpecId, ordersGood.getSpecId());
            shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        }
        Result<String> result = Result.success("添加成功");
        HashMap<String, Long> map = new HashMap<>();
        map.put("orderId", orderId);
        result.setMap(map);
        return result;
    }


    /**
     * 修改订单
     *
     * @param order
     * @return
     */
    @PutMapping
    public Result<String> change(@RequestBody Orders order) {

        if (order.getStatus().equals("未发货") ) {
            // 代表已经付款
            order.setPayTime(LocalDateTime.now());
        } else if (order.getStatus().equals( "正在路上")) {
            // 代表已经发货未送达
            order.setDeliveryStartTime(LocalDateTime.now());
        } else if (order.getStatus().equals("已送达")) {
            // 代表已经送达
            order.setDeliveryArriveTime(LocalDateTime.now());
        }

        if (orderService.updateById(order))
            return Result.success("修改订单成功");
        else
            return Result.error("修改订单失败");
    }

    /**
     * 分页查询订单数据
     *
     * @param page
     * @param pageSize
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/page")
    public Result<Page<OrdersDto>> page(int page, int pageSize, Long id, String status) {
        //构造分页构造器
        Page<Orders> pageInfo = new Page<Orders>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(id != null, Orders::getId, id);
        queryWrapper.like(status != null, Orders::getStatus, status);
        queryWrapper.orderByDesc(Orders::getCreateTime);
        orderService.page(pageInfo, queryWrapper);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        List<OrdersDto> ordersDtos = pageInfo.getRecords().stream().map(item -> {
            // 在订单中添加商品信息
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            // 获取订单中的商品信息
            LambdaQueryWrapper<OrdersGoods> ordersGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersGoodsLambdaQueryWrapper.eq(OrdersGoods::getOrdersId, item.getId());
            Address address = addressService.getById(item.getAddressId());
            ordersDto.setAddress(address);
            List<OrdersGoods> ordersGoods = ordersGoodsService.list(ordersGoodsLambdaQueryWrapper);
            // 为订单中的商品信息绑定SKU信息
            List<OrdersGoodsDto> ordersGoodsDtos = getSku(ordersGoods);
            ordersDto.setOrdersGoodsDtos(ordersGoodsDtos);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtos);
        return Result.success(ordersDtoPage);

    }

    private List<OrdersGoodsDto> getSku(List<OrdersGoods> ordersGoods) {
        // 为订单中的商品信息绑定SKU信息
        List<OrdersGoodsDto> ordersGoodsDtos = ordersGoods.stream().map(item -> {
            OrdersGoodsDto ordersGoodsDto = new OrdersGoodsDto();
            BeanUtils.copyProperties(item, ordersGoodsDto);
            GoodsSpec goodsSpec = goodsSpecService.getById(item.getSpecId());
            Goods goods = goodsService.getById(goodsSpec.getGoodsId());
            ordersGoodsDto.setGoodsSpec(goodsSpec);
            ordersGoodsDto.setName(goods.getName());
            return ordersGoodsDto;
        }).collect(Collectors.toList());
        return ordersGoodsDtos;
    }
}
